package cn.lyjuan.payment.third.base.pay.chl;

import cn.lyjuan.base.util.SpringContextHolder;
import cn.lyjuan.payment.third.base.pay.enums.SimpleChlEnum;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付渠道扫描器，自动加载{@link IPayChl}的实现类
 */
@Component
public class PayChlScanner implements BeanPostProcessor
{
    private static Map<SimpleChlEnum, IPayChl> CHLS = new HashMap<>();

    @Override
    public Object postProcessBeforeInitialization(Object bean, String className) throws BeansException
    {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String className) throws BeansException
    {
        if (null == bean) return null;

        if (IPayChl.class.isInstance(bean))
        {
            IPayChl chl = (IPayChl) bean;
            CHLS.put(chl.chl(), chl);
        }

        return bean;
    }

    /**
     * 根据渠道获取指定的支付渠道交易功能实现类
     * @param chlEnum
     * @return
     */
    public static IPayChl dispatch(SimpleChlEnum chlEnum)
    {
//        IPayChl chl = CHLS.get(chlEnum);

        IPayChl chl = SpringContextHolder.getBean(chlEnum.getCls());
        if (null == chl)
            throw new RuntimeException("unsupported chl: " + chlEnum);


        return chl;
    }
}
